package dao;

import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import pojo.User;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
//    dao层必须依赖模板类才能进行数据库的操作
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(User user) {
        String sql="insert into user(id,username,password) values(null,?,?)";
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
        System.out.println("新增一个用户");
    }

    @Override
    public void update(User user) {
        String sql="update user SET username=?,password=? WHERE id=?";
        jdbcTemplate.update(sql,user.getUsername(),user.getPassword(),user.getId());
        System.out.println("修改一个用户");
    }

    @Override
    public void delete(int id) {
        String sql="DELETE FROM USER WHERE username=?";
        jdbcTemplate.update(sql,id);
        System.out.println(id + "已删除");
    }

    @Override
    public List<User> findUserAll() {
        String sql="select * from user";
        RowMapper<User> rowMapper=new UserMapper();
        List<User> list=jdbcTemplate.query(sql,rowMapper);
        return list;
    }

    @Override
    public User findUserById(int id) {
        String sql="select * from user where id=?";
        RowMapper<User> rowMapper=new UserMapper();
        User user=jdbcTemplate.queryForObject(sql,rowMapper,id);
        return user;
    }

}

























